package com.we823.project.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.jquery.jqgrid.model.JqGrid;
import com.we823.project.common.web.status.PermissionStatus;
import com.we823.project.core.web.WebConstants;
import com.we823.project.model.BaseModel;
import com.we823.project.repository.service.BaseService;
import com.we823.utils.web.RequestUtil;

public abstract class AbstractBaseController<T extends BaseModel> {
	
	protected String baseUrl = "";
	protected String entityName = "entity";
	
	protected String listUrl = "redirect:list.jspx";
	protected PermissionList permissionList=null;
	
	public BaseService<T,Integer> baseService;
	
	
	public AbstractBaseController(BaseService<T,Integer> baseService){
		this.baseService = baseService;
	}
	
	/**
     * 权限前缀：如sys:user
     * 则生成的新增权限为 sys:user:create
     */
    public void setResourceIdentity(String resourceIdentity) {
        if (!StringUtils.isEmpty(resourceIdentity)) {
            permissionList = PermissionList.newPermissionList(resourceIdentity);
        }
    }
    
	@RequestMapping("preAdd")
	public String preAdd(HttpServletRequest request,Model model){
		
		if (permissionList!=null) {
			permissionList.assertHasCreatePermission();
		}
		return baseUrl + "preAdd";
	}
	
	@RequestMapping("add")
	public String add(HttpServletRequest request,T entity,Model model,BindingResult bindingResult,RedirectAttributes redirectAttributes){
		if (permissionList!=null) {
			permissionList.assertHasCreatePermission();
		}
		baseService.save(entity);
		redirectAttributes.addFlashAttribute(WebConstants.MESSAGE, "添加成功");
		return listUrl;
	}
	
	@RequestMapping("preEdit")
	public String preEdit(HttpServletRequest request,Model model){
		if (permissionList!=null) {
			this.permissionList.assertHasEditPermission();
		}
		
		Integer id = RequestUtil.getValueByParam(request,"id",0);
		T entity = baseService.findOne(id);
		model.addAttribute(entityName,entity);
		return baseUrl + "preEdit";
	}
	
	@RequestMapping("edit")
	public String edit(HttpServletRequest request,Model model,T entity,BindingResult bindingResult,RedirectAttributes redirectAttributes){
		if (permissionList!=null) {
			this.permissionList.assertHasEditPermission();
		}
		Integer id = RequestUtil.getValueByParam(request, "id", 0);
		if(id>0){
			entity.setId(id);
		}
		baseService.update(entity);
		
		redirectAttributes.addFlashAttribute(WebConstants.MESSAGE, "修改成功");
		return listUrl;
	}
	
	@RequestMapping("list")
	public String list(){
		if (permissionList!=null) {
			this.permissionList.assertHasViewPermission();
		}
		return baseUrl + "list";
	}
	
	@RequestMapping("delete")
	public String delete(HttpServletRequest request,Model model,RedirectAttributes redirectAttributes) {
		if (permissionList!=null) {
			this.permissionList.assertHasDeletePermission();
		}
		int id = RequestUtil.getValueByParam(request, "id", 0);
		if (id>0) {
			baseService.delete(id);
		}
		
		redirectAttributes.addFlashAttribute(WebConstants.MESSAGE, "删除成功");
		return listUrl;
	}
	@RequestMapping("getJson")
	@ResponseBody
	public Model getJson(HttpServletRequest request,Model model){
		
		if (permissionList!=null) {
			this.permissionList.assertHasViewPermission();
		}
		
		boolean pageable = RequestUtil.getPageable(request);
		JqGrid<T> jqGrid = new JqGrid<>(request,model);
		PageRequest pageRequest = getPageRequest(jqGrid, request);
		Page<T> dataPage = getData(pageRequest, request, model, pageable);
		if(dataPage!=null){
			jqGrid.setDatarows(dataPage.getContent());
			jqGrid.setRecords(dataPage.getTotalElements());
		}
		jqGrid.flush();
		return model;
	}
	
	protected PageRequest getPageRequest(JqGrid<T> jqGrid,HttpServletRequest request){
		PageRequest pageRequest = null;
		int page = jqGrid.getPage()-1;
		int size = jqGrid.getRows();
		Sort sort = getSort(request);
		if(sort!=null){
			pageRequest = new PageRequest(page, size, sort);
		}else{
			pageRequest = new PageRequest(page, size);
		}
		return pageRequest;
	}
	
	/**
	 * 默认排序方式为jqgrid的指定的排序方式，若不使用默认排序，则覆写此方法
	 * @param request
	 * @return
	 */
	protected Sort getSort(HttpServletRequest request) {
		String sortString = RequestUtil.getValueByParam(request, "sidx","");
		String sortType = RequestUtil.getValueByParam(request, "sord", "asc");
		if(!"".equals(sortString)){
			Direction direction = Direction.fromStringOrNull(sortType);
			Sort sort = new Sort(direction, sortString);
			return sort;
		}else{
			return null;
		}
	}


	public abstract Page<T> getData(PageRequest pageRequest,HttpServletRequest request,Model model,boolean pageable);
	
	protected void check(PermissionStatus permissionStatus) {
		if (permissionList!=null) {
			switch (permissionStatus) {
			case CREATE:
				permissionList.assertHasCreatePermission();
				break;
			case UPDATE:
				permissionList.assertHasUpdatePermission();
				break;
			case DELETE:
				permissionList.assertHasDeletePermission();
				break;
			case VIEW:
				permissionList.assertHasViewPermission();
				break;
			default:
				permissionList.assertHasCreatePermission();
				permissionList.assertHasUpdatePermission();
				permissionList.assertHasDeletePermission();
				permissionList.assertHasViewPermission();
				break;
			}
		}
	}
}
